package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("FoodmaterialService")
@Transactional

public class FoodmaterialServiceImpl extends CmiEmaService implements FoodmaterialService {
	public FoodmaterialServiceImpl() {
	}

	@Transactional
	public Foodmaterial saveFoodmaterial(Foodmaterial foodmaterial) {

		if (foodmaterial.getId() == null) {
			Food food = foodDAO.findFoodById(foodmaterial.getFood().getId());
			Material material = materialDAO.findMaterialById(foodmaterial.getMaterial().getId());

			Foodmaterial existingFoodmaterial = foodmaterialDAO.findFoodmaterialByPhysicalPrimaryKey(food.getId(),
					material.getId(), foodmaterial.getContent());

			foodmaterial.setFood(food);
			foodmaterial.setMaterial(material);

			if (isEquals(foodmaterial, existingFoodmaterial)) {
				return existingFoodmaterial;
			}

			foodmaterial = foodmaterialDAO.store(foodmaterial);
			foodmaterialDAO.flush();

		} else {
			Foodmaterial existingFoodmaterial = foodmaterialDAO.findFoodmaterialByPrimaryKey(foodmaterial.getId());

			foodmaterial = foodmaterialDAO.store(foodmaterial);
			foodmaterialDAO.flush();
		}

		return foodmaterial;
	}

	public void deleteFoodmaterial(Foodmaterial foodmaterial) {
		foodmaterialDAO.remove(foodmaterial);
		foodmaterialDAO.flush();
	}

	@Transactional
	public void deleteFoodmaterials(Set<Integer> deleteFoodmaterialsId) {
		Query query = foodmaterialDAO.createNamedQuery("deleteFoodmaterialsById", -1, -1);
		query.setParameter(1, deleteFoodmaterialsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Foodmaterial> loadFoodmaterials() {
		return foodmaterialDAO.findAllFoodmaterials();

	}

	@Transactional
	public Set<Foodmaterial> loadReferenceFoodmaterials(Set<Foodmaterial> foodmaterials) {
		Iterator<Foodmaterial> foodmaterialsIterator = foodmaterials.iterator();
		Set<Foodmaterial> referencedFoodmaterials = new HashSet<>();
		while (foodmaterialsIterator.hasNext()) {
			Foodmaterial currentFoodmaterial = foodmaterialsIterator.next();

		}
		return referencedFoodmaterials;
	}

	public Set<Foodmaterial> loadFoodmaterialsByIdSet(Set<Integer> foodmaterialIdSet) {

		Iterator<Integer> foodmaterialIdIterator = foodmaterialIdSet.iterator();
		Set<Foodmaterial> foodmaterialSet = new HashSet<>();
		while (foodmaterialIdIterator.hasNext()) {
			Integer id = foodmaterialIdIterator.next();
			Foodmaterial currentFoodmaterial = foodmaterialDAO.findFoodmaterialById(id);
			foodmaterialSet.add(currentFoodmaterial);
		}
		return foodmaterialSet;
	}

	@Transactional
	public List<Foodmaterial> findAllFoodmaterials(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Foodmaterial>(foodmaterialDAO.findAllFoodmaterials(startResult, maxRows));
	}

	@Transactional
	public Foodmaterial findFoodmaterialByPrimaryKey(Integer id) {
		return foodmaterialDAO.findFoodmaterialByPrimaryKey(id);
	}

	@Transactional
	public Integer countFoodmaterials() {
		return ((Long) foodmaterialDAO.createQuerySingleResult("select count(o) from Foodmaterial o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countFoodmaterials(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Foodmaterial.class);
		return ((Long) foodmaterialDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countFoodmaterialsByName(String queryName) {
		Query query = foodmaterialDAO.createNamedQuery("countFoodmaterialsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodmaterialsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Foodmaterial.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFoodmaterialObjectReferencedSet(Foodmaterial foodmaterial) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (foodmaterial.getFood() != null) {

			Set<Integer> foodIds = new HashSet<Integer>();
			foodIds.add(foodmaterial.getFood().getId());
			objectReferencedSetMap.put("foodIds", foodIds);
		}
		if (foodmaterial.getMaterial() != null) {

			Set<Integer> materialIds = new HashSet<Integer>();
			materialIds.add(foodmaterial.getMaterial().getId());
			objectReferencedSetMap.put("materialIds", materialIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFoodmaterialClassReferencedSet(Foodmaterial foodmaterial) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());
		classReferencedSetMap.put("materials", materialDAO.findAllMaterials());

		return classReferencedSetMap;
	}

	public boolean isEquals(Foodmaterial foodmaterial, Object obj) {
		if (obj == foodmaterial)
			return true;
		if (!(obj instanceof Foodmaterial))
			return false;
		Foodmaterial comparedFoodmaterial = (Foodmaterial) obj;
		if (!CheckPropertyEqual(foodmaterial.getFood().getId(), comparedFoodmaterial.getFood().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodmaterial.getMaterial().getId(), comparedFoodmaterial.getMaterial().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodmaterial.getContent(), comparedFoodmaterial.getContent())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

